﻿using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;

namespace HSIA
{
    class DataOrder
    {
        public IntPtr frmHandle;
        DataTable dtOrder;
        //public DataTable dtGatherData;
        public DataTable dtReceiver;
        public DataTable dtSensor;
        //public Hashtable htMeasureType;
        public SetData setData;
        public int iFrequency;
        DatabaseObject dbo;
        public SocketServer tcpServer;
        public string sGatherNo = "";
        public bool blDataFromCall = false;

        public DataOrder(DatabaseObject vdbo)
        {
            dbo = vdbo;
            InitOrder();
        }

        private void InitOrder()
        {
            dtOrder = new DataTable("Order");
            dtOrder.Columns.Add("Name", Type.GetType("System.String"));
            dtOrder.Columns.Add("Head", Type.GetType("System.String"));
            dtOrder.Columns.Add("DataType", Type.GetType("System.Int32"));
            dtOrder.Columns.Add("ReciverNo", Type.GetType("System.String"));
            dtOrder.Columns.Add("EndTag", Type.GetType("System.String"));
            dtOrder.Columns.Add("Caption", Type.GetType("System.String"));
            dtOrder.Columns.Add("IsValue", Type.GetType("System.Int32"));
            dtOrder.Columns.Add("ValueLen", Type.GetType("System.Int32"));
            dtOrder.PrimaryKey = new DataColumn[] { dtOrder.Columns["Name"] };
            dtOrder.LoadDataRow(new object[] { "GatherData", "6855", 1, "", "0D", "采集数据", 0, 0 }, true);
            dtOrder.LoadDataRow(new object[] { "ReciverNo", "6877", 0, "0000", "0D", "查询接收仪编号", 0, 0 }, true);
            dtOrder.LoadDataRow(new object[] { "GatherFrequency", "6888", 0, "", "0D", "查询采集周期", 0, 0 }, true);
            dtOrder.LoadDataRow(new object[] { "Version", "6844", 0, "", "0D", "查询软件版本号", 0, 0 }, true);
            dtOrder.LoadDataRow(new object[] { "SetDateTime", "6866", 0, "", "0D", "设置接收仪时间", 1, 0 }, true);
            dtOrder.LoadDataRow(new object[] { "SetFrequency", "6899", 0, "", "0D", "设置采集周期", 1, 1 }, true);
            dtOrder.LoadDataRow(new object[] { "SetWarnLine", "6822", 2, "", "0D", "设置报警门限", 1, 2 }, true);
            dtOrder.LoadDataRow(new object[] { "SetSensorBit", "6833", 2, "", "0D", "设置传感器位", 0, 0 }, true);
        }

        private int GetHexValue(int iDec)
        {
            int iRet = 0;
            string s = iDec.ToString();
            for (int i = 0; i < s.Length; i++)
            {
                string ss = s[i].ToString();
                iRet = iRet + Convert.ToInt32(ss) * (int)Math.Pow(16, s.Length - 1 - i);
            }
            return iRet;
        }

        public byte[] GetOrder(string sOrderName, string sReciverNo, string sDataType, string sValue, string sflag, ref string sOrder)
        {
            //string sRet = "";
            byte[] byteHex = null;
            DataRow dr = dtOrder.Rows.Find(sOrderName);
            if (dr != null)
            {
                string s = dr["ReciverNo"].ToString();
                if (s == "") s = string.Format("{0:x}", Convert.ToInt32(sReciverNo)).PadLeft(4, '0');
                int iDataType = Convert.ToInt32(dr["DataType"]);
                if (iDataType == 1)
                {
                    if (sflag.Trim() != "") s = "0" + sflag + s; else s = "03" + s;
                }
                else if (iDataType == 2) s = s + sDataType;
                string sData = dr["Head"].ToString() + s;

                if (dr["IsValue"].ToString() == "1")
                {
                    int iValueLen = Convert.ToInt32(dr["ValueLen"]);
                    if (iValueLen != 0)
                    {
                        int iValue = Convert.ToInt32(sValue);
                        string sHex = string.Format("{0:X}", iValue);
                        sHex = sHex.PadLeft(iValueLen * 2, '0');
                        sData = sData + sHex;
                        if (dr["Name"].ToString() == "SetWarnLine")
                            sData = sData + "0000";
                    }
                    else
                    {
                        if (sValue.Length > 0)
                        {
                            for (int i = 0; i < sValue.Length; i = i + 2)
                            {
                                string sByte = string.Format("{0:X}", Convert.ToInt32(sValue.Substring(i, 2)));
                                sByte = sByte.PadLeft(2, '0');
                                sData = sData + sByte;
                            }
                        }
                    }
                }

                int iLen = sData.Length / 2;
                byteHex = new byte[iLen + 2];
                int j = 0; int iByte = 0;//int iSum = 0;
                for (int i = 0; i < sData.Length; i = i + 2)
                {
                    string sByte = sData.Substring(i, 2);
                    iByte = Convert.ToInt32(sByte, 16);
                    byteHex[j] = Convert.ToByte(iByte);
                    sOrder = sOrder + " " + sByte;
                    //iSum = iSum + iByte;
                    j++;
                }
                int iCRC;
                string sCRC = GetCRC(byteHex, 0, out iCRC);// string.Format("{0:X}", iSum);
                byteHex[j] = Convert.ToByte(iCRC);
                sOrder = sOrder + " " + sCRC;
                string sEndTag = dr["EndTag"].ToString();
                byteHex[byteHex.Length - 1] = Convert.ToByte(Convert.ToInt32(sEndTag, 16));
                sOrder = sOrder + " " + sEndTag;
            }
            return byteHex;
        }

        public byte[] GetOrderByteFromString(ref string sOrder)
        {
            string sData = sOrder.Replace(" ", "");
            int iLen = sData.Length / 2;
            byte[] byteHex = new byte[iLen + 2];
            int j = 0; int iByte = 0;//int iSum = 0;
            for (int i = 0; i < sData.Length; i = i + 2)
            {
                string sByte = sData.Substring(i, 2);
                iByte = Convert.ToInt32(sByte, 16);
                byteHex[j] = Convert.ToByte(iByte);
                //sOrder = sOrder + " " + sByte;
                j++;
            }
            int iCRC;
            string sCRC = GetCRC(byteHex, 0, out iCRC);// string.Format("{0:X}", iSum);
            byteHex[j] = Convert.ToByte(iCRC);
            sOrder = sOrder + " " + sCRC + " 0D";
            byteHex[byteHex.Length - 1] = Convert.ToByte(Convert.ToInt32("0D", 16));
            return byteHex;
        }

        public byte[] GetOrderSMSFromString(ref string sOrder)
        {
            string sData = sOrder.Replace(" ", "");
            int iLen = sData.Length / 2;
            byte[] byteHex = new byte[iLen + 2];
            int j = 0; int iByte = 0;//int iSum = 0;
            for (int i = 0; i < sData.Length; i = i + 2)
            {
                string sByte = sData.Substring(i, 2);
                iByte = Convert.ToInt32(sByte, 16);
                byteHex[j] = Convert.ToByte(iByte);
                //sOrder = sOrder + " " + sByte;
                j++;
            }
            int iCRC;
            string sCRC = GetCRC(byteHex, 0, out iCRC);// string.Format("{0:X}", iSum);
            byteHex[j] = Convert.ToByte(iCRC);
            sOrder = sOrder + sCRC;
            return byteHex;
        }

        public bool CRC(byte[] byteHex, int iLastBit)
        {
            int iCRC;
            string sCRC = GetCRC(byteHex, iLastBit, out iCRC);
            return byteHex[byteHex.Length - iLastBit] == iCRC;
        }

        public bool CRC16(byte[] byteHex, int iLastBit)
        {
            byte CRC_H, CRC_L;
            GetCRC16(byteHex, iLastBit, out CRC_H, out CRC_L);
            return byteHex[byteHex.Length - 1 - iLastBit] == CRC_H && byteHex[byteHex.Length - iLastBit] == CRC_L;
        }

        private string GetCRC(byte[] byteHex, int iLastBit, out int iCRC)
        {
            int iSum = 0; int iLen = byteHex.Length - iLastBit;
            for (int i = 0; i < iLen; i++)
            {
                iSum = iSum + Convert.ToInt32(byteHex[i]);
            }
            string sCRC = string.Format("{0:X}", iSum);
            if (sCRC.Length < 2) sCRC = sCRC.PadLeft(2, '0');
            else if (sCRC.Length > 2) sCRC = sCRC.Substring(sCRC.Length - 2, 2);

            iCRC = Convert.ToInt32(sCRC, 16);
            return sCRC;
        }

        public byte[] GetCRC16(byte[] data, int iLastBit, out byte CRC_H, out byte CRC_L)
        {
            CRC_L = 0xFF;
            CRC_H = 0xFF;   //CRC寄存器 
            byte SH;
            byte SL;
            byte[] temp = data;
            int j;

            for (int i = 0; i < temp.Length - iLastBit; i++)
            {
                CRC_L = (byte)(CRC_L ^ temp[i]);     //每一个数据与CRC寄存器进行异或 
                for (j = 0; j < 8; j++)
                {
                    SH = (byte)(CRC_H & 0x01);
                    SL = (byte)(CRC_L & 0x01);

                    CRC_H = (byte)(CRC_H >> 1);      //高位右移一位
                    CRC_H = (byte)(CRC_H & 0x7F);
                    CRC_L = (byte)(CRC_L >> 1);      //低位右移一位 
                    CRC_L = (byte)(CRC_L & 0x7F);

                    if (SH == 0x01)                  //如果高位字节最后一位为1 
                    {
                        CRC_L = (byte)(CRC_L | 0x80);//则低位字节右移后前面补1 
                    }                                //否则自动补0 
                    if (SL == 0x01)                  //如果LSB为1,则与多项式码进行异或 
                    {
                        CRC_H = (byte)(CRC_H ^ 0xA0);
                        CRC_L = (byte)(CRC_L ^ 0x01);
                    }
                }
            }
            byte[] CRC = new byte[2];
            CRC[0] = CRC_L;       //CRC高位 
            CRC[1] = CRC_H;       //CRC低位 
            return MergerArray(data, CRC);
        }

        public byte[] MergerArray(byte[] First, byte[] Second)
        {
            byte[] result = new byte[First.Length + Second.Length];
            First.CopyTo(result, 0);
            Second.CopyTo(result, First.Length);
            return result;
        }

        public byte[] GetOrderReceiver(string sOrder)
        {
            string sData = sOrder.Replace(" ", "");
            int iLen = sData.Length / 2;
            byte[] byteHex = new byte[iLen + 2];
            int j = 0; int iByte = 0;//int iSum = 0;
            for (int i = 0; i < sData.Length; i = i + 2)
            {
                string sByte = sData.Substring(i, 2);
                iByte = Convert.ToInt32(sByte, 16);
                byteHex[j] = Convert.ToByte(iByte);
                //sOrder = sOrder + " " + sByte;
                j++;
            }
            int iCRC;
            string sCRC = GetCRC(byteHex, 0, out iCRC);// string.Format("{0:X}", iSum);
            byteHex[j] = Convert.ToByte(iCRC);
            sOrder = sOrder + " " + sCRC + " 0D";
            byteHex[byteHex.Length - 1] = Convert.ToByte(Convert.ToInt32("0D", 16));
            return byteHex;
        }

        private void AddReceiverRow(int iReciverNo, string psIP, int iType)
        {
            DataRow drNew = dtReceiver.NewRow();
            drNew["ReceiverNo"] = iReciverNo;
            drNew["IPCOM"] = psIP;
            drNew["Type"] = iType;
            drNew["Frequency"] = iFrequency;
            drNew["Online"] = dbo.GetLanguage(195);//"在线";
            drNew["GatherFrequency"] = DateTime.Now.ToString();
            dtReceiver.Rows.Add(drNew);
        }

        private void RefreshReceiver(int iReciverNo, string psIP)
        {
            lock (dtReceiver)  //换成HASHTABLE
            {
                DataRow dr = dtReceiver.Rows.Find(iReciverNo);
                if (dr == null)
                {
                    if (psIP.StartsWith("COM"))
                    {
                        AddReceiverRow(iReciverNo, psIP, 1);
                        dbo.ExcuteSQL("insert into Receiver(ReceiverNo,IPCOM,Type,Frequency) values(" + iReciverNo + ",'" + psIP + "',1," + iFrequency + ")");
                    }
                    else
                    {
                        AddReceiverRow(iReciverNo, psIP, 0);
                        dbo.ExcuteSQL("insert into Receiver(ReceiverNo,IPCOM,Type,Frequency) values(" + iReciverNo + ",'" + psIP + "',0," + iFrequency + ")");
                    }
                }
                else
                {
                    if (dr["IPCOM"].ToString() != psIP)
                    {
                        if (psIP.StartsWith("COM"))
                        {
                            dbo.ExcuteSQL("update Receiver set IPCOM='" + psIP + "',Type=1 where ReceiverNo=" + iReciverNo);
                            dr["Type"] = 1;
                        }
                        else
                        {
                            dbo.ExcuteSQL("update Receiver set IPCOM='" + psIP + "',Type=0 where ReceiverNo=" + iReciverNo);
                            dr["Type"] = 0;
                        }
                        dr["IPCOM"] = psIP;
                    }
                    if (dr["Online"].ToString() != dbo.GetLanguage(195)) dr["Online"] = dbo.GetLanguage(195);//"在线";"在线"
                }
            }
        }

        private void RefreshGatherDate(int iReciverNo, string psIP)
        {
            lock (dtReceiver)  //换成HASHTABLE
            {
                DataRow dr = dtReceiver.Rows.Find(iReciverNo);
                if (dr != null)
                {
                    dr["GatherFrequency"] = DateTime.Now.ToString();
                    dr["Online"] = dbo.GetLanguage(195);
                    dr["IPCOM"] = psIP;
                    dbo.ExcuteSQL("update Receiver set IPCOM='" + psIP + "',Type=0 where ReceiverNo=" + iReciverNo);
                }
            }
        }

        private void RefreshReceiver(int iReciverNo)
        {
            lock (dtReceiver)  //换成HASHTABLE
            {
                DataRow dr = dtReceiver.Rows.Find(iReciverNo);
                if (dr == null)
                {
                    AddReceiverRow(iReciverNo, "COM", 1);
                    dbo.ExcuteSQL("insert into Receiver(ReceiverNo,IPCOM,Type,Frequency) values(" + iReciverNo + ",'COM',1," + iFrequency + ")");
                }
                else
                {
                    dr["GatherFrequency"] = DateTime.Now.ToString();
                    if (dr["Type"].ToString() != "1")
                    {
                        dbo.ExcuteSQL("update Receiver set IPCOM='COM',Type=1 where ReceiverNo=" + iReciverNo);
                        dr["Type"] = 1;
                    }
                    if (dr["Online"].ToString() != dbo.GetLanguage(195)) dr["Online"] = dbo.GetLanguage(195);//"在线";  "在线"
                }
            }
        }

        public string UDR(byte[] byteHex, string psIP, string sSensorIDs)//处理接收到的数据
        {
            string sRet = "";
            if ((byteHex == null) || (byteHex.Length == 0)) return dbo.GetLanguage(189) + ":NULL";//无效数据
            string sHead = "";
            if (byteHex.Length > 2) sHead = string.Format("{0:X}", byteHex[1]).PadLeft(2, '0') + string.Format("{0:X}", byteHex[0]).PadLeft(2, '0');
            int iReciverNo = 0;
            if (sHead == "6855")
            {
                iReciverNo = Convert.ToInt32(byteHex[3]) * 256 + Convert.ToInt32(byteHex[4]);
            }
            else
            {
                if (byteHex.Length > 4) iReciverNo = Convert.ToInt32(byteHex[2]) * 256 + Convert.ToInt32(byteHex[3]);
            }
            AmateBussiness.ToLog("DataHex", sGatherNo, byteHex);
            if (iReciverNo >= 0x3E8) return dbo.GetLanguage(189) + ":OUT";//超出范围
            switch (sHead)
            {
                case "6877"://查询接收仪编号
                    RefreshReceiver(iReciverNo, psIP);
                    break;
                #region 6855//采集数据
                case "6855":
                    //if (!CRC(byteHex, 2) && !CRC(byteHex, 1)) { return iReciverNo + " : CRC"; }//rd.sResult = "CRC校验出错!";

                    GatherData_GPS_2(byteHex, psIP, iReciverNo, sSensorIDs);
                    if (psIP == "COM") RefreshReceiver(iReciverNo);
                    else RefreshGatherDate(iReciverNo, psIP);

                    PC.SendFormMessage(frmHandle, (uint)PC.WM_LanchWarn, (uint)100, (uint)100);
                    break;
                #endregion

                case "6888"://查询采集周期
                    int iGatherFrequency = Convert.ToInt32(byteHex[4]);
                    lock (dtReceiver)
                    {
                        DataRow dr = dtReceiver.Rows.Find(iReciverNo);
                        if (dr != null)
                        {
                            if ((dr["Frequency"] == DBNull.Value) || (dr["Frequency"].ToString() != iGatherFrequency.ToString()))
                            {
                                dr["Frequency"] = iGatherFrequency;
                                dbo.ExcuteSQL("update Receiver set Frequency=" + iGatherFrequency + " where ReceiverNo='" + iReciverNo + "'");
                            }
                        }
                    }
                    break;
                case "6844"://查询软件版本号
                    //lock (dtReceiver)
                    //{
                    //    DataRow dr = dtReceiver.Rows.Find(iReciverNo);
                    //    if (dr != null)
                    //    {
                    string s = "";
                    for (int i = 4; i < byteHex.Length - 1; i++)
                    {
                        if (Convert.ToInt32(byteHex[i]) == 13) break;
                        s = s + (char)byteHex[i];
                    }
                    s = s.Replace(" ", "");
                    //dr["Version"] = s;
                    FrmVersion frm = new FrmVersion();
                    frm.richTextBox1.Text = dbo.GetLanguage(237) + ":" + iReciverNo.ToString() + "\r\n";//接收仪
                    frm.richTextBox1.AppendText(dbo.GetLanguage(340) + ":" + s);//版本号
                    frm.ShowDialog();
                    //if ((dr["Version"] == DBNull.Value)|| (dr["Version"].ToString().Trim() != s))
                    //{
                    //    dr["Version"] = s;
                    //    dbo.ExcuteSQL("update Receiver set Version='" + s + "' where ReceiverNo='" + iReciverNo + "'");
                    //}
                    //    }
                    //}
                    break;
                case "6866"://设置接收仪时间                    
                    sRet = dbo.GetLanguage(237) + iReciverNo + dbo.GetLanguage(60);// "接收仪 " " 时钟设置成功!";
                    //MessageBox.Show(sRet);
                    break;
                case "6899"://设置采集周期
                    sRet = dbo.GetLanguage(238);// "接收仪采集周期设置成功!";
                    break;
                case "6822"://设置报警门限
                    sRet = dbo.GetLanguage(242);//"接收仪报警门限设置成功!";
                    break;
                case "6833"://设置传感器位
                    sRet = dbo.GetLanguage(241);//"接收仪传感器位设置成功!";
                    break;
                default:
                    sRet = dbo.GetLanguage(327);// "未知的命令格式,执行失败!";
                    break;
            }

            return iReciverNo + " : " + sRet;
        }

        private void GatherData_GPS_1(byte[] byteHex, string psIP, int iReciverNo, string sSensorIDs)//协议1.0
        {
            string strtmp = "";
            if (byteHex.Length > 3) strtmp = string.Format("{0:X}", byteHex[2]).PadLeft(2, '0');

            string sGatherDate = PublicFunc.GetUniformDateString(DateTime.Now);
            if (sGatherNo == "" || !blDataFromCall) sGatherNo = sGatherDate;// return "未采集数据!";
            //DataTable dt = dbo.GetDataTableBySql("select  count(ID) CNT from GatherData where gatherno='" + sGatherNo + "' and  receiverno= '" + iReciverNo + "'", "GatherData");
            //if (Convert.ToInt32(dt.Rows[0]["CNT"]) > 0) return "数据已采集!";// dbo.GetLanguage();//
            PC.SendFormMessage(frmHandle, (uint)PC.WM_GatherData, (uint)iReciverNo, (uint)1);
            int iSetClick = 0;
            string sql = "";
            Int16 item = 0;
            int iBegin = 7;
            double dLat = 0.0;
            double dLng = 0.0;
            string sSpeed = "";
            string[] sM = new string[dbo.dtMeasureType.Rows.Count];

            //string sFlag = Convert.ToString(byteHex[2], 2).PadLeft(8, '0');
            int iCount = Convert.ToInt32(byteHex[5]) * 256 + Convert.ToInt32(byteHex[6]);

            switch (strtmp)
            {
                case "01":
                case "02":
                case "03":
                case "81":
                case "82":
                case "83": iBegin = 7; iCount = Convert.ToInt32(byteHex[5]) * 256 + Convert.ToInt32(byteHex[6]); break;
                case "41":
                case "42":
                case "43":
                    iBegin = 17;
                    iCount = Convert.ToInt32(byteHex[16]);

                    dLat = byteHex[5] + Convert.ToDouble(byteHex[6]) / 60 + Convert.ToDouble((byteHex[7] * 256 + byteHex[8])) / 3600000 - Units.dLat;
                    dLng = byteHex[9] + Convert.ToDouble(byteHex[10]) / 60 + Convert.ToDouble((byteHex[11] * 256 + byteHex[12])) / 3600000 + Units.dLng;

                    string sflag = Convert.ToString(byteHex[13], 2).PadLeft(4, '0');

                    dLat = (Convert.ToInt32(sflag.Substring(0, 2), 2) == 0) ? dLat : -dLat;
                    dLng = (Convert.ToInt32(sflag.Substring(2, 4), 2) == 1) ? dLng : -dLng;
                    if (dLat > 0xFF && dLng > 0xFF)
                    {
                        dLat = dLng = 0.0;
                        break;
                    }
                    double dSpeed = (Convert.ToDouble(byteHex[14]) * 256 + Convert.ToDouble(byteHex[15])) * 0.1852;
                    if (dSpeed <= 120) sSpeed = dSpeed.ToString();
                    break;
                case "C1":
                case "C2":
                case "C3":
                    iBegin = 20;
                    iCount = Convert.ToInt32(byteHex[19]);
                    string strDate = DateTime.Now.ToString("yyyy-MM-dd") + " " + Convert.ToInt32(byteHex[5]) + ":" + Convert.ToInt32(byteHex[6]) + ":" + Convert.ToInt32(byteHex[7]);
                    try
                    {
                        DateTime dtGet = Convert.ToDateTime(strDate);
                        TimeSpan tSpan = DateTime.Now - dtGet;
                        if (tSpan.TotalMinutes <= 10 && tSpan.TotalMinutes >= -10) sGatherDate = strDate;
                    }
                    catch { }

                    dLat = byteHex[8] + Convert.ToDouble(byteHex[9]) / 60 + Convert.ToDouble((byteHex[10] * 256 + byteHex[11])) / 3600000 - Units.dLat;
                    dLng = byteHex[12] + Convert.ToDouble(byteHex[13]) / 60 + Convert.ToDouble((byteHex[14] * 256 + byteHex[15])) / 3600000 + Units.dLng;
                    if (dLat > 0xFF && dLng > 0xFF)
                    {
                        dLat = dLng = 0.0;
                        sGatherDate = PublicFunc.GetUniformDateString(DateTime.Now);
                        break;
                    }
                    sflag = Convert.ToString(byteHex[16], 2).PadLeft(4, '0');
                    dLat = (Convert.ToInt32(sflag.Substring(0, 2), 2) == 0) ? dLat : -dLat;
                    dLng = (Convert.ToInt32(sflag.Substring(2, 2), 2) == 1) ? dLng : -dLng;

                    dSpeed = (Convert.ToDouble(byteHex[17]) * 256 + Convert.ToDouble(byteHex[18])) * 0.1852;
                    if (dSpeed <= 120)
                    {
                        sM[0] = sSpeed = dSpeed.ToString();
                    }
                    break;
            }
            string sOKSensorIDs = "";
            List<string[]> LSQL1 = new List<string[]>();
            List<string[]> LSQL2 = new List<string[]>();
            int iSensorNo = 0;
            for (int i = 0; i < iCount; i++)
            {
                iSensorNo = Convert.ToInt32(byteHex[iBegin]) * 256 + Convert.ToInt32(byteHex[iBegin + 1]);
                string sID = iReciverNo + "-" + iSensorNo;
                //if (sSensorIDs.IndexOf("," + sID + ",") < 0 || sOKSensorIDs.IndexOf("," + sID + ",") > -1)
                //{
                //    switch (strtmp)
                //    {
                //        case "01":  //不带时钟温度   
                //        case "41":  //带GPS温度    
                //        case "C1":  //带时钟GPS温度                                   
                //            iBegin = iBegin + 5;
                //            break;
                //        case "02":  //不带时钟湿度    
                //        case "42":  //带GPS湿度    
                //        case "C2":  //带时钟GPS湿度                                   
                //            iBegin = iBegin + 5;
                //            break;
                //        case "03":  //不带时钟湿度温度   
                //        case "43":  //带GPS温度湿度    
                //        case "C3":  //带时带GPS温湿度                                   
                //            iBegin = iBegin + 7;
                //            break;

                //        case "81":  //带时钟温度                                   
                //            iBegin = iBegin + 11;
                //            break;
                //        case "82":  //带时钟湿度                                    
                //            iBegin = iBegin + 11;
                //            break;
                //        case "83":  //带时钟湿度                                   
                //            iBegin = iBegin + 13;
                //            break;

                //        default: break;
                //    }
                //    continue;
                //}
                ////if (sOKSensorIDs.IndexOf("," + sID + ",") >-1) continue;
                sOKSensorIDs = sOKSensorIDs + "," + sID + ",";
                int iData = 0;
                double dDataT = -51.0;
                double dDataH = -51.0;
                string sDataT = string.Empty;
                string sDataH = string.Empty;
                switch (strtmp)
                {
                    case "01":  //不带时钟温度
                    case "41":  //带GPS温度    
                    case "C1":  //带时钟GPS温度                                   
                        {
                            if (PublicFunc.dbo_Measure.LastIndexOf("T") == -1)
                            {
                                iBegin = iBegin + 5;
                                break;
                            }
                            iData = Convert.ToInt32(byteHex[iBegin + 3]) * 256 + Convert.ToInt32(byteHex[iBegin + 4]);
                            item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                            dDataT = ((double)item) / 10.0;
                            //string sID = iReciverNo + "-" + iSensorNo;
                            //sbGatherData.Append(sGatherDataInsert + "('" + DateTime.Now.ToString() + "','" + sGatherNo + "','" + sID + "','" + iReciverNo + "'," + dData + ",null);");
                            //sbGatherData.Append(sSensorLastTH + "('" + sID + "'," + dData + ",null);");
                            iBegin = iBegin + 5;
                        }
                        break;

                    case "02":  ////不带时钟湿度
                    case "42":  //带GPS湿度    
                    case "C2":  //带时钟GPS湿度                                   
                        {
                            if (PublicFunc.dbo_Measure.LastIndexOf("H") > -1)
                            {
                                iData = Convert.ToInt32(byteHex[iBegin + 3]) * 256 + Convert.ToInt32(byteHex[iBegin + 4]);
                                item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                                dDataH = ((double)item) / 10.0;
                                //string sID = iReciverNo + "-" + iSensorNo;
                                //sbGatherData.Append(sGatherDataInsert + "('" + DateTime.Now.ToString() + "','" + sGatherNo + "','" + sID + "','" + iReciverNo + "',null," + dDataH + ");");
                                iBegin = iBegin + 5;
                            }
                        }
                        break;

                    case "03":  ////不带时钟湿度温度
                    case "43":  //带GPS温度湿度    
                    case "C3":  //带时带GPS温湿度                                   
                        {
                            if (PublicFunc.dbo_Measure.LastIndexOf("T") > -1)
                            {
                                iData = Convert.ToInt32(byteHex[iBegin + 5]) * 256 + Convert.ToInt32(byteHex[iBegin + 6]);
                                item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                                dDataT = ((double)item) / 10.0;
                            }
                            //string sID = iReciverNo + "-" + iSensorNo;
                            if (PublicFunc.dbo_Measure.LastIndexOf("H") > -1)
                            {
                                int iDataH = Convert.ToInt32(byteHex[iBegin + 3]) * 256 + Convert.ToInt32(byteHex[iBegin + 4]);
                                Int16 itemH = Convert.ToInt16(string.Format("{0:x}", iDataH), 16);
                                dDataH = ((double)itemH) / 10.0;
                            }
                            //sbGatherData.Append(sGatherDataInsert + "('" + DateTime.Now.ToString() + "','" + sGatherNo + "','" + sID + "','" + iReciverNo + "'," + dData + "," + dDataH + ");");
                            iBegin = iBegin + 7;
                        }
                        break;

                    case "81":  //带时钟温度
                        {
                            string sReyear = Convert.ToInt32(byteHex[iBegin + 3]).ToString();
                            string syear = sGatherDate.Substring(2, 2);
                            string strDate = "20" + sReyear + "-" + Convert.ToInt32(byteHex[iBegin + 4]) + "-" +
                                    Convert.ToInt32(byteHex[iBegin + 5]) + " " + Convert.ToInt32(byteHex[iBegin + 6]) + ":" +
                                    Convert.ToInt32(byteHex[iBegin + 7]) + ":" + Convert.ToInt32(byteHex[iBegin + 8]);
                            if (sReyear != syear)
                            {
                                DataTable dtSetClick = dbo.GetDataTableBySql("select * from SetClick where ReceiverNo='" + iReciverNo + "'", "SetClick");
                                if ((dtSetClick.Rows.Count == 0) && (iSetClick == 0))
                                {
                                    sql = "insert into SetClick(ReceiverNo) values('" + iReciverNo + "');";
                                    iSetClick = iSetClick + 1;
                                }
                            }
                            else sGatherDate = strDate;
                            iData = Convert.ToInt32(byteHex[iBegin + 9]) * 256 + Convert.ToInt32(byteHex[iBegin + 10]);
                            item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                            dDataT = ((double)item) / 10.0;
                            //string sID = iReciverNo + "-" + iSensorNo;
                            //sbGatherData.Append(sGatherDataInsert + "('"+DateTime.Now.ToString()+"','" + sGatherNo + "','" + sID + "','" + iReciverNo + "'," + dData + ",null);");
                            //sbGatherData.Append(sSensorLastTH + "('" +  sID + "'," + dData + ",null);");
                            iBegin = iBegin + 11;
                        }
                        break;

                    case "82":  //带时钟湿度
                        {
                            string sReyear = Convert.ToInt32(byteHex[iBegin + 3]).ToString();
                            string syear = sGatherDate.Substring(2, 2);
                            string strDate = "20" + sReyear + "-" + Convert.ToInt32(byteHex[iBegin + 4]) + "-" +
                                    Convert.ToInt32(byteHex[iBegin + 5]) + " " + Convert.ToInt32(byteHex[iBegin + 6]) + ":" +
                                    Convert.ToInt32(byteHex[iBegin + 7]) + ":" + Convert.ToInt32(byteHex[iBegin + 8]);
                            if (sReyear != syear)
                            {
                                DataTable dtSetClick = dbo.GetDataTableBySql("select * from SetClick where ReceiverNo='" + iReciverNo + "'", "SetClick");
                                if ((dtSetClick.Rows.Count == 0) && (iSetClick == 0))
                                {
                                    sql = "insert into SetClick(ReceiverNo) values('" + iReciverNo + "');";
                                    iSetClick = iSetClick + 1;
                                }
                            }
                            else sGatherDate = strDate;
                            iData = Convert.ToInt32(byteHex[iBegin + 9]) * 256 + Convert.ToInt32(byteHex[iBegin + 10]);
                            item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                            dDataH = ((double)item) / 10.0;
                            //string sID = iReciverNo + "-" + iSensorNo;
                            //sbGatherData.Append(sGatherDataInsert + "('" + DateTime.Now.ToString() + "','" + sGatherNo + "','" + sID + "','" + iReciverNo + "',null," + dDataH + ");");
                            iBegin = iBegin + 11;
                        }
                        break;

                    case "83":  //带时钟湿度
                        {
                            string sReyear = Convert.ToInt32(byteHex[iBegin + 3]).ToString();
                            string syear = sGatherDate.Substring(2, 2);
                            string strDate = "20" + sReyear + "-" + Convert.ToInt32(byteHex[iBegin + 4]) + "-" +
                                    Convert.ToInt32(byteHex[iBegin + 5]) + " " + Convert.ToInt32(byteHex[iBegin + 6]) + ":" +
                                    Convert.ToInt32(byteHex[iBegin + 7]) + ":" + Convert.ToInt32(byteHex[iBegin + 8]);
                            if (sReyear != syear)
                            {
                                DataTable dtSetClick = dbo.GetDataTableBySql("select * from SetClick where ReceiverNo='" + iReciverNo + "'", "SetClick");
                                if ((dtSetClick.Rows.Count == 0) && (iSetClick == 0))
                                {
                                    sql = "insert into SetClick(ReceiverNo) values('" + iReciverNo + "');";
                                    iSetClick = iSetClick + 1;
                                }
                            }
                            else sGatherDate = strDate;
                            iData = Convert.ToInt32(byteHex[iBegin + 11]) * 256 + Convert.ToInt32(byteHex[iBegin + 12]);
                            item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                            dDataT = ((double)item) / 10.0;
                            int iDataH = Convert.ToInt32(byteHex[iBegin + 9]) * 256 + Convert.ToInt32(byteHex[iBegin + 10]);
                            Int16 itemH = Convert.ToInt16(string.Format("{0:x}", iDataH), 16);
                            dDataH = ((double)itemH) / 10.0;
                            //string sID = iReciverNo + "-" + iSensorNo;
                            //sbGatherData.Append(sGatherDataInsert + "('" + DateTime.Now.ToString() + "','" + sGatherNo + "','" + sID + "','" + iReciverNo + "'," + dData + "," + dDataH + ");");
                            iBegin = iBegin + 13;
                        }
                        break;

                    default:
                        break;
                }
                //sbGatherData.Append(sGatherDataInsert + "('" + DateTime.Now.ToString() + "','" + sGatherNo + "','" + sID + "','" + iReciverNo + "'," + dData + "," + dDataH + ");");
                //sbGatherData.Append(string.Format(sSensorLastTH, sID, dData, dDataH));
                if (dDataT != -51.0) sM[1] = sDataT = dDataT.ToString();
                if (dDataH != -51.0) sM[2] = sDataH = dDataH.ToString();
                string[] sbt = PublicFunc.MergerArray(new string[] { sGatherDate, sGatherNo, sID, iReciverNo.ToString(), dLat.ToString(), dLng.ToString() }, sM);
                sbt = PublicFunc.MergerArray(sbt, PublicFunc.dbo_W);
                LSQL1.Add(sbt);
                sbt = PublicFunc.MergerArray(new string[] { sID, sGatherDate, dLat.ToString(), dLng.ToString() }, sM);
                sbt = PublicFunc.MergerArray(sbt, PublicFunc.dbo_W);
                LSQL2.Add(sbt);
            }
            if (iCount > 0)
            {
                PC.SendFormMessage(frmHandle, (uint)PC.WM_GatherData, (uint)iReciverNo, (uint)2);
                if (sql != "") dbo.ExcuteSQL(sql);
                dbo.ExcuteSqlCommand(LSQL1, "InsertDatas");
                dbo.ExcuteSqlCommand(LSQL2, "SensorXYs1");
                //if (sql != "") dbo.ExcuteSQL(sbGatherData.ToString() + sql);
                //else dbo.ExcuteSQL(sbGatherData.ToString());
                PC.SendFormMessage(frmHandle, (uint)PC.WM_GatherData, (uint)iReciverNo, (uint)3);
            }
        }

        private void GatherData_GPS_2(byte[] byteHex, string psIP, int iReciverNo, string sSensorIDs)//协议2.0
        {
            string sFlag = "";
            string sflag = "";
            if (byteHex.Length > 3) sFlag = Convert.ToString(byteHex[2], 2).PadLeft(8, '0');

            string sID = iReciverNo + "-1";

            string sSQL = "update SensorXY set X=null,Y=null," + string.Format(PublicFunc.dbo_Measure, "Last", "=null") + " where ID = '" + sID + "'";
            dbo.ExcuteSQL(sSQL);

            string sGatherDate = PublicFunc.GetUniformDateString(DateTime.Now);
            if (sGatherNo == "" || !blDataFromCall) sGatherNo = sGatherDate;// return "未采集数据!";
            //DataTable dt = dbo.GetDataTableBySql("select  count(ID) CNT from GatherData where gatherno='" + sGatherNo + "' and  receiverno= '" + iReciverNo + "'", "GatherData");
            //if (Convert.ToInt32(dt.Rows[0]["CNT"]) > 0) return "数据已采集!";// dbo.GetLanguage();//
            PC.SendFormMessage(frmHandle, (uint)PC.WM_GatherData, (uint)iReciverNo, (uint)1);

            //int iSetClick = 0;
            string sql = "";
            int iBegin = 5;
            string sDate = DateTime.Now.ToString();
            double dLat = 0.0;
            double dLng = 0.0;
            string[] sM = null;
            List<string[]> LsM = new List<string[]>();
            if (sFlag[0].ToString() == "1")//时间格式
            {
                sDate = Convert.ToInt32(byteHex[iBegin]) + "-" + Convert.ToInt32(byteHex[iBegin + 1]) + "-" + Convert.ToInt32(byteHex[iBegin + 2]) + " " +
                        Convert.ToInt32(byteHex[iBegin + 3]) + ":" + Convert.ToInt32(byteHex[iBegin + 4]) + ":" + Convert.ToInt32(byteHex[iBegin + 5]);
                iBegin += 6;
            }
            else
            {
                sDate = DateTime.Now.ToString("yyyy-MM-dd") + " " + Convert.ToInt32(byteHex[iBegin]) + ":" + Convert.ToInt32(byteHex[iBegin + 1]) + ":" + Convert.ToInt32(byteHex[iBegin + 2]);
                iBegin += 3;
            }
            if (sFlag[1].ToString() == "1")//定位信息
            {
                if (sFlag[2].ToString() == "1")//定位方式
                {
                    dLat = byteHex[iBegin] + Convert.ToDouble(byteHex[iBegin + 1]) / 60 + Convert.ToDouble((byteHex[iBegin + 2] * 256 + byteHex[iBegin + 3])) / 3600000 - Units.dLat;
                    dLng = byteHex[iBegin + 4] + Convert.ToDouble(byteHex[iBegin + 5]) / 60 + Convert.ToDouble((byteHex[iBegin + 6] * 256 + byteHex[iBegin + 7])) / 3600000 + Units.dLng;

                    sflag = Convert.ToString(byteHex[iBegin + 8], 2).PadLeft(4, '0');

                    dLat = (Convert.ToInt32(sflag.Substring(0, 2), 2) == 0) ? dLat : -dLat;
                    dLng = (Convert.ToInt32(sflag.Substring(2, 2), 2) == 0) ? dLng : -dLng;
                    if (dLat > 0xFF && dLng > 0xFF) dLat = dLng = 0.0;

                    if (dbo.dtMeasureType.Rows.Find(Units.Si) != null)//速度
                    {
                        sM = new string[1];
                        double dSpeed = (Convert.ToDouble(byteHex[iBegin + 9]) * 256 + Convert.ToDouble(byteHex[iBegin + 10])) * 0.1852;
                        if (dSpeed <= 120) sM[0] = dSpeed.ToString();
                        LsM.Add(sM);
                    }
                    if (dbo.dtMeasureType.Rows.Find(Units.Ai) != null)//航向
                    {
                        sM = new string[1];
                        double dCourse = Convert.ToInt32(byteHex[iBegin + 11]) * 256 + Convert.ToInt32(byteHex[iBegin + 12]);
                        if (dCourse >= 0 && dCourse < 360) sM[0] = dCourse.ToString();
                        LsM.Add(sM);
                    }
                    iBegin += 13;
                }
                else
                {
                    CellIDString cid = new CellIDString();
                    cid.lac = (Convert.ToInt32(byteHex[iBegin + 4]) * 256 + Convert.ToInt32(byteHex[iBegin + 5])).ToString();
                    cid.cellid = (Convert.ToInt32(byteHex[iBegin + 6]) * 256 + Convert.ToInt32(byteHex[iBegin + 7])).ToString();

                    if (tcpServer.locate_GoogleMapAPI(cid, out dLat, out dLng))
                    {
                    }
                    else if (tcpServer.locate_JuHeAPI(cid, out dLat, out dLng))
                    {
                    }
                    if (dLat > 0xFF && dLng > 0xFF) dLat = dLng = 0.0;

                    sM = new string[1];
                    if (dbo.dtMeasureType.Rows.Find(Units.Si) != null)//速度
                        LsM.Add(sM);
                    if (dbo.dtMeasureType.Rows.Find(Units.Ai) != null)//航向
                        LsM.Add(sM);
                    iBegin += 8;
                }
            }
            if (sFlag[3].ToString() == "1")//电池电量
            {
                if (dbo.dtMeasureType.Rows.Find(Units.Bi) != null)
                {
                    sM = new string[1];

                    sflag = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0');
                    iBegin += 1;
                    int iBattery = Convert.ToInt32(sflag.Substring(1, 7), 2);
                    if (sflag[0].ToString() == "1") //外部电源
                    {
                        iBattery = -iBattery;
                    }
                    else
                    {
                    }
                    if (iBattery >= -100 && iBattery <= 100) sM[0] = iBattery.ToString();
                    LsM.Add(sM);
                }
            }

            sflag = PublicFunc.ReverseStr(Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0')); iBegin += 1;//传感器种类

            if (dbo.dtMeasureType.Rows.Find(Units.Di) != null)
            {
                sM = new string[1];
                sM[0] = byteHex[iBegin + 1].ToString();//开门量
                iBegin += 2;
                LsM.Add(sM);
            }

            int iLen = sflag.IndexOf("1");
            int iMeasure = dbo.dtMeasureType.Rows.Count;
            for (int iIndex = 1; iIndex <= iMeasure; iIndex++)
            {
                DataRow dr = dbo.dtMeasureType.Rows[iMeasure - iIndex];
                if (dr["ID"].ToString() == "S" || dr["ID"].ToString() == "A" || dr["ID"].ToString() == "B" || dr["ID"].ToString() == "D") continue;//特殊固定变量
                sM = new string[Convert.ToInt32(dr["Cnum"])];
                if (sflag[iIndex - 1].ToString() != "1")
                {
                    LsM.Add(sM);
                    continue;
                }

                int iSensorCount = byteHex[iBegin]; iBegin += 1;//传感器路数

                double dData = -51.0;
                Int32 iData = 0;
                Int16 item = 0;

                for (int i = 0; i < iSensorCount; i++)
                {
                    if (i > sM.Length) continue;
                    iData = Convert.ToInt32(byteHex[iBegin]) * 256 + Convert.ToInt32(byteHex[iBegin + 1]);
                    item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                    dData = ((double)item) / 8.0;

                    if (dData < 100 && dData > -100) sM[i] = dData.ToString();
                    if (iBegin + 2 >= byteHex.Length) break;
                    else iBegin += 2;
                }
                LsM.Add(sM);
            }

            List<string[]> LSQL1 = new List<string[]>();
            List<string[]> LSQL2 = new List<string[]>();

            sM = new string[0];
            foreach (string[] s in LsM) sM = PublicFunc.MergerArray(sM, s);

            string[] sbt = PublicFunc.MergerArray(new string[] { sGatherDate, sGatherNo, sID, iReciverNo.ToString(), dLat.ToString(), dLng.ToString() }, sM);
            sbt = PublicFunc.MergerArray(sbt, PublicFunc.dbo_W);
            LSQL1.Add(sbt);

            sbt = PublicFunc.MergerArray(new string[] { sID, sGatherDate, dLat.ToString(), dLng.ToString() }, sM);
            sbt = PublicFunc.MergerArray(sbt, PublicFunc.dbo_W);
            LSQL2.Add(sbt);

            if (iLen != -1)
            {
                PC.SendFormMessage(frmHandle, (uint)PC.WM_GatherData, (uint)iReciverNo, (uint)2);
                if (sql != "") dbo.ExcuteSQL(sql);
                dbo.ExcuteSqlCommand(LSQL1, "InsertDatas");
                dbo.ExcuteSqlCommand(LSQL2, "SensorXYs1");
                //if (sql != "") dbo.ExcuteSQL(sbGatherData.ToString() + sql);
                //else dbo.ExcuteSQL(sbGatherData.ToString());
                PC.SendFormMessage(frmHandle, (uint)PC.WM_GatherData, (uint)iReciverNo, (uint)3);
            }

        }

        public string GetSMSReciverNo(string msg)
        {
            string sRet = "";
            int iCount = 0;
            int iData = 0;
            double dData = 0;
            double dDataH = 0;
            int iReciverNo = 0;
            List<string[]> LSQL1 = new List<string[]>();
            List<string[]> LSQL2 = new List<string[]>();
            string sGatherDate = PublicFunc.GetUniformDateString(DateTime.Now);
            try
            {
                iReciverNo = Convert.ToInt32(msg.Substring(0, 2)) * 256 + Convert.ToInt32(msg.Substring(2, 2));
                msg = msg.Substring(4, msg.Length - 4);
                string[] Msg = msg.Split(';');
                foreach (string s in Msg)
                {
                    string iSensorNo = s.Substring(0, s.IndexOf(":"));
                    dData = Convert.ToDouble(s.Substring(s.IndexOf(":", s.IndexOf(":") - s.IndexOf("'C"))));
                    string sID = iReciverNo.ToString() + "-" + iSensorNo.ToString();

                    string[] sbt = new string[] { sGatherDate, sGatherNo, sID, iReciverNo.ToString(), dData.ToString(), dDataH.ToString() };
                    LSQL1.Add(sbt);
                    sbt = new string[] { dData.ToString(), dDataH.ToString(), sID };
                    LSQL2.Add(sbt);
                    iCount++;
                }
            }
            catch
            {
                sRet = "KO";
            }
            if (iCount > 0)
            {
                PC.SendFormMessage(frmHandle, (uint)PC.WM_GatherData, (uint)iReciverNo, (uint)2);
                //if (sql != "") dbo.ExcuteSQL(sql);
                dbo.ExcuteSqlCommand(LSQL1, "InsertDatas");
                dbo.ExcuteSqlCommand(LSQL2, "SensorXYs1");
                PC.SendFormMessage(frmHandle, (uint)PC.WM_GatherData, (uint)iReciverNo, (uint)3);
                sRet = "OK";
            }
            return sRet;
        }

    }
}
